#include "datawidget.h"
#include "models/robot.h"
#include <QVBoxLayout>
#include <QHeaderView>
#include <QJsonArray>
#include <QDebug>
#include <QTimer>
#include <QLabel>
#include <mainwindow.h>
#include <models/robotlist.h>


DataWidget::DataWidget(QWidget *parent):
    QWidget(parent)
{
    table = new QTableWidget(this);
    // 设置窗口背景颜色
    this->setStyleSheet(QString("QWidget { background-color: %1; border-image: none;border: 0px; }").arg(backgroundColor));
}

void DataWidget::setColor(QString background, QString border)
{
    backgroundColor=background;
    borderColor=border;
}

void DataWidget::setupUI()
{

    // 创建水平布局来放置标签和表格
    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    mainLayout->setSpacing(0);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 创建表格
    table->setFixedHeight(height());
    table->setRowCount(m_labels.size());
    table->verticalHeader()->hide();
    // 禁用水平和垂直滚动条
    table->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    table->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    // 禁用选择和焦点
    table->setSelectionMode(QAbstractItemView::NoSelection);
    table->setFocusPolicy(Qt::NoFocus);
    // 表格样式设置
    QString tableStyle = QString(
                "QTableWidget {"
                "    background-color: %1;"
                "    border: 1px solid %2;"
                "    color: white;"
                "    gridline-color: %2;"
                "    border-image: none;"
                "    border-right: none;"
                "    border-bottom: none;"
                "}"
                "QHeaderView::section {"
                "    background-color: %1;"
                "    padding: 5px;"
                "    border: 1px  %2;"
                "    border-image: none;"
                "    font: %3px '微软雅黑';"
                "}"
                "QTableWidget::item {"
                "    background-color: %1;"
                "    border-image: none;"
                "    border: 1px  %2;"
                "}"
                "QHeaderView {"
                "    background-color: %1;"
                "    border-image: none;"
                "}"
                "QHeaderView::section:horizontal {"
                "    background-color: %1;"
                "    border: 1px solid %2;"
                "    border-left: none;"
                "    border-top: none;"
                "    border-image: none;"
                "}"
                ).arg(backgroundColor).arg(borderColor).arg(int(18*g_yScale));

    QFont font = this->font();
    font.setFamily("微软雅黑");
    font.setPixelSize(18* g_yScale);
    table->setFont(font);
    table->horizontalHeader()->setFont(font);
    table->setStyleSheet(tableStyle);
    // 设置表格属性
    table->setAlternatingRowColors(false);
    table->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    int nItemHeight=(height()-1)/(m_labels.size()+1);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    table->horizontalHeader()->setFixedHeight(nItemHeight);           // 固定表头高度;
    table->verticalHeader()->setMinimumSectionSize(nItemHeight);
    table->verticalHeader()->setDefaultSectionSize(nItemHeight);
    mainLayout->addWidget(table);

}

void DataWidget::setJointType(JointType tempJointType)
{
    m_labels.clear();
    curJointType=tempJointType;
    switch (curJointType) {
    case HEAD_JOINT:
    case WAIST_JOINT:
    case LEFT_ARM_JOINT:
    case RIGHT_ARM_JOINT:
    case LEFT_LEG_JOINT:
    case RIGHT_LEG_JOINT:
        m_labels<<"位姿"<< "速度"<<"力矩"<<"温度"<<"状态"<<"错误码";
        break;
    case LEFT_TOOL_JOINT:
    case RIGHT_TOOL_JOINT:
    case LEFT_TOOL_HAND_JOINT: //左手 灵巧手
    case LEFT_TOOL_GRIPPER_JOINT: //左手 夹爪
    case LEFT_TOOL_SUCKER_JOINT: //左手 吸盘
    case RIGHT_TOOL_HAND_JOINT: //右手 灵巧手
    case RIGHT_TOOL_GRIPPER_JOINT: //右手 夹爪
    case RIGHT_TOOL_SUCKER_JOINT: //右手 吸盘
    {
        m_labels<<"位姿"<<"速度"<<"力矩";
        break;
    }
    case LEFT_TIP_JOINT:
    case RIGHT_TIP_JOINT:
    default:
        m_labels<<"位姿";
        break;
    }
    QVector<JOINT> joints= getJointByType(curJointType);
    if (joints.isEmpty())
        return;
    QStringList nameList;
    nameList.append(getJointTypeText(curJointType));
    //末端没有期望
    for(int i=0;i<joints.size();i++)
    {
        QString str = joints[i].strName;
        if(curJointType != LEFT_TIP_JOINT && curJointType != RIGHT_TIP_JOINT)
        {
            str += "(实际/期望)";
        }
        nameList.append(str);
    }
    // 更新表格大小
    table->setColumnCount(nameList.size());
    // 更新表头
    table->setHorizontalHeaderLabels(nameList);

    QTableWidgetItem *headerItem = table->horizontalHeaderItem(0);
    if (headerItem)
        headerItem->setForeground(QBrush(QColor(9, 140, 255, 255)));
    for(int i = 1; i < nameList.size(); ++i)
    {
        QTableWidgetItem *headerItem = table->horizontalHeaderItem(i);
        if (headerItem)
            headerItem->setForeground(QBrush(QColor(255, 255, 255, 255)));

        table->horizontalHeader()->setSectionResizeMode(i,QHeaderView::Stretch);
    }
}

void DataWidget::updateData()
{
    if (!table)
        return;
    table->clearContents();
    for (int row=0;row<m_labels.size();row++) {
        QTableWidgetItem *item = new QTableWidgetItem(m_labels[row]);
        item->setTextAlignment(Qt::AlignCenter);
        table->setItem(row,0,item);
        table->setColumnWidth(0,80*g_xScale);
    }
    QVector<JOINT> joints= getJointByType(curJointType);
    if (joints.isEmpty())
        return;

    Robot *pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
    {
        switch (curJointType)
        {
        case LEFT_TIP_JOINT:
        {
            QVector<float> leftTip = pCurRobot->leftTip();
            for (int column = 0; column < leftTip.size() && column < joints.size();column++ ) {
                QString itemText = QString::number(leftTip[joints[column].nIndex], 'f', 2) ;
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(0,column+1,item);
            }
        }
            break;
        case RIGHT_TIP_JOINT:
        {
            QVector<float> rightTip = pCurRobot->rightTip();
            for (int column = 0; column < rightTip.size()&& column < joints.size();column++ ) {
                QString itemText = QString::number(rightTip[joints[column].nIndex], 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(0,column+1,item);
            }
        }
            break;
        case LEFT_TOOL_HAND_JOINT:
        case LEFT_TOOL_GRIPPER_JOINT:
        case LEFT_TOOL_SUCKER_JOINT:
        {
            QVector<float> fArcs = pCurRobot->leftFingerArc();
            QVector<float> fArcsExp = pCurRobot->leftFingerArcExp();
            for (int column = 0; column < fArcs.size()&&column < fArcsExp.size()&& column < joints.size();column++ ) {
                QString itemText = QString::number(fArcs[joints[column].nIndex] /** 180/M_PI*/, 'f', 2) + "/" +
                        QString::number(fArcsExp[joints[column].nIndex] /**180/M_PI*/, 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(0,column+1,item);
            }
            QVector<float> fSpeeds = pCurRobot->leftFingerSpeed();
            QVector<float> fSpeedsExp = pCurRobot->leftFingerSpeedExp();
            for (int column = 0; column < fSpeeds.size()&&column < fSpeedsExp.size()&& column < joints.size();column++ ) {
                QString itemText = QString::number(fSpeeds[joints[column].nIndex], 'f', 2) + "/" +
                        QString::number(fSpeedsExp[joints[column].nIndex], 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(1,column+1,item);
            }
            QVector<float> fMoments = pCurRobot->leftFingerMoment();
            QVector<float> fMomentsExp = pCurRobot->leftFingerMomentExp();
            for (int column = 0; column < fMoments.size()&&column < fMomentsExp.size()&& column < joints.size();column++ ) {
                QString itemText = QString::number(fMoments[joints[column].nIndex], 'f', 2) + "/" + QString::number(fMomentsExp[joints[column].nIndex], 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(2,column+1,item);
            }
        }
            break;
        case RIGHT_TOOL_HAND_JOINT:
        case RIGHT_TOOL_GRIPPER_JOINT:
        case RIGHT_TOOL_SUCKER_JOINT:
        {
            QVector<float> fArcs = pCurRobot->rightFingerArc();
            QVector<float> fArcsExp = pCurRobot->rightFingerArcExp();
            for (int column = 0; column < fArcs.size()&&column < fArcsExp.size()&&  column < joints.size();column++ ) {
                QString itemText = QString::number(fArcs[joints[column].nIndex] /** 180/M_PI*/, 'f', 2) + "/" +
                        QString::number(fArcsExp[joints[column].nIndex] /** 180/M_PI*/, 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(0,column+1,item);
            }
            QVector<float> fSpeeds = pCurRobot->rightFingerSpeed();
            QVector<float> fSpeedsExp = pCurRobot->rightFingerSpeedExp();
            for (int column = 0; column < fSpeeds.size()&&column < fSpeedsExp.size()&&  column < joints.size();column++ ) {
                QString itemText = QString::number(fSpeeds[joints[column].nIndex], 'f', 2) + "/" + QString::number(fSpeedsExp[joints[column].nIndex], 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(1,column+1,item);
            }
            QVector<float> fMoments = pCurRobot->rightFingerMoment();
            QVector<float> fMomentsExp = pCurRobot->rightFingerMomentExp();
            for (int column = 0; column < fMoments.size()&&column < fMomentsExp.size()&&  column < joints.size();column++ ) {
                QString itemText = QString::number(fMoments[joints[column].nIndex], 'f', 2) + "/" + QString::number(fMomentsExp[joints[column].nIndex], 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(2,column+1,item);
            }
        }
            break;
        default:
        {
            QBrush  itemColor=QBrush(QColor(Qt::red));
            SportState SportState=pCurRobot->SportStateData();
            //第1行：角度
            for (int column = 0; column < joints.size();column++ ) {
                QString itemText = QString::number(SportState.realArc[joints[column].nIndex] * 180/M_PI, 'f', 2)+"/"+QString::number(SportState.expArc[joints[column].nIndex] * 180/M_PI, 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(0,column+1,item);
            }
            //第2行：速度
            for (int column = 0; column < joints.size();column++ ) {
                QString itemText = QString::number(SportState.realSpeed[joints[column].nIndex], 'f', 2)+"/"+QString::number(SportState.expSpeed[joints[column].nIndex], 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(1,column+1,item);
            }
            //第3行：力矩
            for (int column = 0; column < joints.size();column++ ) {
                QString itemText = QString::number(SportState.realMoment[joints[column].nIndex], 'f', 2)+"/"+QString::number(SportState.expMoment[joints[column].nIndex], 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(2,column+1,item);
            }
            //第4行：温度
            for (int column = 0; column < joints.size();column++ ) {
                float temp=SportState.tempture[joints[column].nIndex];
                QString itemText = QString::number(temp, 'f', 2);
                QTableWidgetItem *item =new QTableWidgetItem(itemText);
                if(temp>WARNING_TEMPTURE) //判断是否超过告警值
                    itemColor=QBrush(QColor(Qt::red));
                else
                    itemColor=QBrush(QColor(Qt::green));
                item->setForeground(itemColor);
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(3,column+1,item);
            }
            //第5行：状态
            for (int column = 0; column < joints.size();column++ ) {
                QTableWidgetItem *item =new QTableWidgetItem();
                switch(int(SportState.state[joints[column].nIndex])&0x000000ff)
                {
                case 0:
                    item->setText("——");
                    item->setForeground(QBrush(QColor(Qt::green)));
                    break;
                case 0x18:
                    item->setText("错误");
                    item->setForeground(QBrush(QColor(Qt::red)));
                    break;
                case 0x31:
                    item->setText("就绪");
                    item->setForeground(QBrush(QColor(Qt::green)));
                    break;
                case 0x33:
                    item->setText("开启");
                    item->setForeground(QBrush(QColor(Qt::green)));
                    break;
                case 0x37:
                    item->setText("使能");
                    item->setForeground(QBrush(QColor(Qt::green)));
                    break;
                case 0x50:
                    item->setText("正常");
                    item->setForeground(QBrush(QColor(Qt::green)));
                    break;
                default:
                    item->setText(QString("未知-%1").arg(int(SportState.state[joints[column].nIndex])));
                    item->setForeground(QBrush(QColor(Qt::red)));
                    break;
                }
                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(4,column+1,item);
            }
            //第6行：错误码
            for (int column = 0; column < joints.size();column++ ) {
                QTableWidgetItem *item =new QTableWidgetItem();
                QString strErr="";//错误码
                switch(int(SportState.error[joints[column].nIndex]))
                {
                case 0: strErr += "——"; break;
                case 0x2311: strErr += "过流"; break;
                case 0x2340: strErr += "短路(电机接线或其他异常、驱动器故障)"; break;
                case 0x3120: strErr += "⽋压"; break;
                case 0x3130: strErr += "相位丢失"; break;
                case 0x3310: strErr += "过压"; break;
                case 0x4310: strErr += "驱动器过热"; break;
                case 0x7121: strErr += "电机卡住"; break;
                case 0x7300: strErr += "反馈错误"; break;
                case 0x8130: strErr += "⼼跳事件"; break;
                case 0x8140: strErr += "从总线断开恢复"; break;
                case 0x8311: strErr += "超过峰值电流"; break;
                case 0x8480: strErr += "速度跟踪错误"; break;
                case 0x8611: strErr += "位置跟踪错误"; break;
                case 0xFF10: strErr += "不能启动电机"; break;
                case 0xFF20: strErr += "安全模式打开"; break;
                default: strErr+="未知错误";break;
                }
                item->setText(strErr);
                item->setForeground(strErr!="——"?QBrush(QColor(Qt::red)):QBrush(QColor(Qt::green)));

                item->setTextAlignment(Qt::AlignCenter);
                table->setItem(5,column+1,item);
            }


        }

        }
    }
}

void DataWidget::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    Robot* pCurRobot=RobotList::getInstance()->getCurRobot();
    if(pCurRobot)
        connect(pCurRobot,&Robot::sportStateChanged, this, &DataWidget::updateData,Qt::UniqueConnection);

    if(m_bFirst)
    {
        m_bFirst=false;
        setupUI();//初始化
        // 先显示表格以确保能获取正确的表头高度
        table->horizontalHeader()->show();
        table->show();
    }

    QWidget::showEvent(event);
}
